/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： report-manage
 * 文件名称： UserGeneTestingServiceImpl.java
 * Date：18-11-6 下午3:06
 * Author: guomw
 */

package com.guomw.report.service.service.impl;

import com.guomw.report.service.entity.UserGeneTesting;
import com.guomw.report.service.models.PageView;
import com.guomw.report.service.models.Searcher;
import com.guomw.report.service.repository.UserGeneTestingRepository;
import com.guomw.report.service.service.UserGeneTestingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author guomw
 * @date 2018/11/6
 */
@Service
public class UserGeneTestingServiceImpl implements UserGeneTestingService {
    @Autowired
    private UserGeneTestingRepository userGeneTestingRepository;

    @Override
    public PageView<UserGeneTesting> searchList(Searcher searcher) {
        Pageable pageable = new PageRequest(searcher.getPageIndex() - 1, searcher.getPageSize(), new Sort(Sort.Direction.ASC, "createTime"));
        Specification<UserGeneTesting> specification = (root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (searcher.getStatus() != -1) {
                predicates.add(builder.equal(root.get("status").as(int.class), searcher.getStatus()));
            }
            predicates.add(builder.equal(root.get("useStatus").as(int.class), 1));
            if (!StringUtils.isEmpty(searcher.getKeyword())) {
                predicates.add(builder.like(root.get("userName").as(String.class), "%" + searcher.getKeyword() + "%"));
            }
            if (!StringUtils.isEmpty(searcher.getBarCode())) {
                predicates.add(builder.like(root.get("barCode").as(String.class), "%" + searcher.getBarCode() + "%"));
            }
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<UserGeneTesting> page = userGeneTestingRepository.findAll(specification, pageable);
        PageView<UserGeneTesting> pageView = new PageView<>();
        pageView.setPageCount(page.getTotalPages());
        pageView.setTotalCount(page.getTotalElements());
        pageView.setList(page.getContent());
        return pageView;
    }
}
